package com.ygkj.demo.view

import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.RelativeLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2

/**
 * 自定义 fragment 额bannner
 * @constructor
 */
class CustomBanner @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
    private var viewPager2: ViewPager2 = ViewPager2(context)
    private var pagerScrollDuration: Long = 0
    private var isUserInputEnabled: Boolean = false
    private lateinit var onPageChangeCallback: ViewPager2.OnPageChangeCallback

    init {
//        viewPager2 = ViewPager2(context)
        viewPager2.setLayoutParams(
            ViewGroup.LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT
            )
        )
        setisUserInputEnabled(isUserInputEnabled)
        setOffscreenPageLimit(1)
        setAdapter(ArrayList<Fragment>())
        addView(viewPager2)
    }

    fun setOffscreenPageLimit(limit: Int): CustomBanner? {
        viewPager2.offscreenPageLimit = limit
        return this
    }

    fun setPagerScrollDuration(pagerScrollDuration: Long): CustomBanner? {
        this.pagerScrollDuration = pagerScrollDuration
        return this
    }

    fun setisUserInputEnabled(isUserInputEnabled: Boolean): CustomBanner? {
        viewPager2.isUserInputEnabled = isUserInputEnabled
        return this
    }

    fun setHandlerDelay(index: Int, time: Long) {
        handler.postDelayed(Runnable {
            viewPager2.setCurrentItem(index, false)
        }, pagerScrollDuration)
    }


    fun setonPageChangeCallback(ob: ViewPager2.OnPageChangeCallback): CustomBanner {
        viewPager2.registerOnPageChangeCallback(ob)
        return this
    }

    fun setAdapter(list: ArrayList<Fragment>) {
        viewPager2.adapter = object : FragmentStateAdapter(context as FragmentActivity) {
            override fun getItemCount(): Int = list.size
            override fun createFragment(position: Int): Fragment = list[position]
        }
    }

    fun getViewPage() = viewPager2
}